/*
 * @Author: wangjun haodreams@163.com
 * @Date: 2024-07-08 16:38:10
 * @LastEditors: wangjun haodreams@163.com
 * @LastEditTime: 2024-07-09 11:24:35
 * @FilePath: \golib\fontx\fontx.go
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package xfont

import (
	"bytes"
	"os"

	"github.com/golang/freetype/truetype"
	"golang.org/x/image/font"
	"golang.org/x/image/math/fixed"
)

type Font struct {
	name     string
	Style    string //B,I,U  Bold Italic Underline
	size     int
	lastSize int
	face     font.Face
	font     *truetype.Font
	fontData []byte
}

func NewFont(name string, path string) (m *Font, err error) {
	fontData, err := os.ReadFile(path)
	if err != nil {
		return
	}
	return New(name, fontData)
}

func New(name string, fontData []byte) (m *Font, err error) {
	font, err := truetype.Parse(fontData)
	if err != nil {
		return
	}
	m = new(Font)
	m.font = font
	m.fontData = fontData
	m.SetSize(12)
	return
}

func (m *Font) Name() string {
	return m.name
}

func (m *Font) SetSize(size int) {
	m.size = size
	if m.size != m.lastSize {
		m.lastSize = m.size
		m.face = truetype.NewFace(m.font, &truetype.Options{Size: float64(m.size)})
	}
}

func (m *Font) Size() int {
	return m.size
}

func (m *Font) LastSize() int {
	return m.lastSize
}

func (m *Font) SetFont(f *truetype.Font) {
	m.font = f
}

func (m *Font) GetFont() *truetype.Font {
	return m.font
}

func (m *Font) FontData() []byte {
	return m.fontData
}

func (m *Font) Height() int {
	return m.face.Metrics().Height.Ceil()
}

// 按照固定长度换行
func (m *Font) Lines(text string, width int) (lines []string, height int) {
	var x fixed.Int26_6
	wh := fixed.I(width)
	buf := bytes.NewBuffer(nil)
	for _, r := range text {
		ad, ok := m.face.GlyphAdvance(r)
		if ok {
			if (x + ad) > wh {
				lines = append(lines, buf.String())
				buf.Reset()
				x = 0
			}
			buf.WriteRune(r)
			x += ad
		}
	}
	if buf.Len() > 0 {
		lines = append(lines, buf.String())
	}
	height = m.face.Metrics().Height.Ceil()
	return
}

// measureText 计算文本的宽度
func (m *Font) MeasureText(text string) (width fixed.Int26_6, height int) {
	for _, r := range text {
		ad, ok := m.face.GlyphAdvance(r)
		if ok {
			width += ad // fixed.I(ad.Ceil())
			continue
		}
	}
	return width, m.face.Metrics().Height.Ceil()
}
